<?php
class UserProfilesController extends AppController
{
    public $name = 'UserProfiles';
    public $uses = array(
        'UserProfile',
        'Attachment',
        'EmailTemplate'
    );
    public $components = array(
        'Email'
    );
    public function beforeFilter()
    {
        $this->Security->disabledFields = array(
            'UserAvatar.filename',
            'City.id',
            'State.id',
			'UserProfile.country_id',
			'UserProfile.latitude',
			'UserProfile.longitude',
			'State.name',
			'City.name',
            'UserWebsite'
        );
        parent::beforeFilter();
    }
    public function edit($user_id = null)
    {  
        $this->pageTitle = __l('Edit Profile');
        $this->UserProfile->User->UserAvatar->Behaviors->attach('ImageUpload', Configure::read('avatar.file'));
		 
        if (!empty($this->request->data)) {
		
            if (empty($this->request->data['User']['id'])) {
			
                $this->request->data['User']['id'] = $this->Auth->user('id');
            }
			
            $user = $this->UserProfile->User->find('first', array(
                'conditions' => array(
                    'User.id' => $this->request->data['User']['id']
                ) ,
                'contain' => array(
                    'UserProfile',
                    'UserAvatar' => array(
                        'fields' => array(
                            'UserAvatar.id',
                            'UserAvatar.filename',
                            'UserAvatar.dir',
                            'UserAvatar.width',
                            'UserAvatar.height'
                        )
                    ) ,
                    'UserWebsite'
                ) ,
                'recursive' => 0
            ));
			
            if (!empty($user)) {
                $this->request->data['UserProfile']['id'] = $user['UserProfile']['id'];
                if (!empty($user['UserAvatar']['id'])) {
                    $this->request->data['UserAvatar']['id'] = $user['UserAvatar']['id'];
                }
            }
            $this->request->data['UserProfile']['user_id'] = $this->request->data['User']['id'];
            if (!empty($this->request->data['UserAvatar']['filename']['name'])) {
                $this->request->data['UserAvatar']['filename']['type'] = get_mime($this->request->data['UserAvatar']['filename']['tmp_name']);
            }
            if (!empty($this->request->data['UserAvatar']['filename']['name']) || (!Configure::read('avatar.file.allowEmpty') && empty($this->request->data['UserAvatar']['id']))) {
                $this->UserProfile->User->UserAvatar->set($this->request->data);
            }
			
            // validating UserWebsite data
            $is_website_valid = true;
			$this->UserProfile->User->UserWebsite->deleteAll($this->request->data['User']['id']);
            foreach($this->request->data['UserWebsite'] as $key => $userWebsite) {
				$data['UserWebsite']['website'] = $userWebsite['website'];
				$this->UserProfile->User->UserWebsite->set($data);
				if (!$this->UserProfile->User->UserWebsite->validates()) {
					$UserWebsiteValidationError[$key] = $this->UserProfile->User->UserWebsite->validationErrors;
					$is_website_valid = false;
					$this->Session->setFlash(__l('UserWebsite could not be added. Please, try again.') , 'default', null, 'error');
				}
            }
            unset($this->UserProfile->User->UserWebsite->validationErrors);
            if (!empty($UserWebsiteValidationError)) {
                foreach($UserWebsiteValidationError as $key => $error) {
                    $this->UserProfile->User->UserWebsite->validationErrors[$key] = $error;
                }
            }
            $this->UserProfile->set($this->request->data);
			
            $this->UserProfile->User->set($this->request->data);
			
			if (empty($this->request->data['UserProfile']['country_id'])) {
				unset($this->UserProfile->validate['country_id']);
			}
			if (!empty($this->request->data['UserProfile']['country_id'])) {
				$this->request->data['UserProfile']['Country']['iso2'] = $this->request->data['UserProfile']['country_id'];
			}
			if (!empty($this->request->data['State']['name'])) {
	            $this->UserProfile->State->set($this->request->data);
			}
			if (!empty($this->request->data['City']['name'])) {
	            $this->UserProfile->City->set($this->request->data);
			}
            $ini_upload_error = 1;
            if ($this->request->data['UserAvatar']['filename']['error'] == 1) {
                $ini_upload_error = 0;
            }
            $paypal_account = 1;
            if (!empty($this->request->data['UserProfile']['paypal_account']) && ($user['UserProfile']['paypal_account'] != $this->request->data['UserProfile']['paypal_account'] || $user['UserProfile']['paypal_first_name'] != $this->request->data['UserProfile']['paypal_first_name'] || $user['UserProfile']['paypal_last_name'] != $this->request->data['UserProfile']['paypal_last_name'])) {
                $this->loadModel('Payment');
                $rsPayStatus = $this->Payment->getVerifiedStatus($this->request->data['UserProfile']);
                if (strtoupper($rsPayStatus['responseEnvelope.ack']) != 'SUCCESS' || strtoupper($rsPayStatus['accountStatus']) != 'VERIFIED') {
                    $this->Session->setFlash(__l('Enter verified PayPal email and the name associated with it') , 'default', null, 'error');
                    $paypal_account = 0;
                    $this->UserProfile->validationErrors['paypal_account'] = __l('Enter verified PayPal email and the name associated with it');
                }
            }
            if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin && empty($this->request->data['UserProfile']['paypal_account']) && !empty($user['User']['project_count'])) {
                $this->Session->setFlash(__l('PayPal account should not be empty.') , 'default', null, 'error');
                $this->UserProfile->validationErrors['paypal_account'] = __l('Enter verified PayPal email and the name associated with it');
            } elseif ($this->UserProfile->User->validates() & $this->UserProfile->validates() & $this->UserProfile->User->UserAvatar->validates() & $this->UserProfile->City->validates() & $this->UserProfile->State->validates() && $ini_upload_error && $is_website_valid && $paypal_account) {
				if (!empty($this->request->data['UserProfile']['country_id'])) {
					$this->request->data['UserProfile']['country_id'] = $this->UserProfile->Country->findCountryId($this->request->data['UserProfile']['country_id']);
				}
                $this->request->data['State']['country_id'] = $this->request->data['UserProfile']['country_id'];
                $this->request->data['UserProfile']['state_id'] = !empty($this->request->data['State']['id']) ? $this->request->data['State']['id'] : $this->UserProfile->State->findOrSaveAndGetIdWithArray($this->request->data['State']['name'], $this->request->data['State']);
                $this->request->data['City']['state_id'] = $this->request->data['UserProfile']['state_id'];
                $this->request->data['City']['country_id'] = $this->request->data['UserProfile']['country_id'];
                $this->request->data['UserProfile']['city_id'] = !empty($this->request->data['City']['id']) ? $this->request->data['City']['id'] : $this->UserProfile->City->findOrSaveAndGetIdWithArray($this->request->data['City']['name'], $this->request->data['City']);
                if ($this->UserProfile->save($this->request->data)) {
				
                    $this->UserProfile->User->save($this->request->data['User']);
					
                    $this->UserProfile->User->UserWebsite->deleteAll(array(
                        'UserWebsite.user_id' => $this->request->data['User']['id']
                    ));
                    if (!empty($this->request->data['UserWebsite'])) {
                        foreach($this->request->data['UserWebsite'] as $userWebsite) {
							if(!empty($userWebsite['website'])) {
								$data['UserWebsite']['user_id'] = $this->request->data['User']['id'];
								$data['UserWebsite']['website'] = $userWebsite['website'];
								$this->UserProfile->User->UserWebsite->create();
								$this->UserProfile->User->UserWebsite->save($data);
							}
                        }
                    }
                    if (!empty($this->request->data['UserAvatar']['filename']['name'])) {
                        $this->Attachment->create();
                        $this->request->data['UserAvatar']['class'] = 'UserAvatar';
                        $this->request->data['UserAvatar']['foreign_id'] = $this->request->data['User']['id'];
                        $this->Attachment->save($this->request->data['UserAvatar']);
                    }
                }
                
				
                if (($this->Auth->user('user_type_id') == ConstUserTypes::Admin and Configure::read('user.is_mail_to_user_for_profile_edit')) or Configure::read('UserPermissionPreference.blog_mail_send')) {
                    // Send mail to user to activate the account and send account details
                    $emailFindReplace = array(
                        '##USERNAME##' => $user['User']['username'],
                        '##SITE_NAME##' => Configure::read('site.name') ,
                        '##SITE_URL##' => Router::url('/', true) ,
                    );
                    $email = $this->EmailTemplate->selectTemplate('Admin User Edit');
                    //$this->Email->from = strtr($email['from'], $emailFindReplace);
                    $this->Email->from = ($email['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email['from'];
                    $this->Email->to = $user['User']['email'];
                    $this->Email->subject = strtr($email['subject'], $emailFindReplace);
                    $this->Email->send(strtr($email['email_content'], $emailFindReplace));
					
					
                }
			$this->Session->setFlash(__l('User Profile has been updated') , 'default', null, 'success');
			$this->redirect(array('controller'=>'user_profiles','action'=>'edit',$this->request->data['User']['id']));
            } else {
                if ($this->request->data['UserAvatar']['filename']['error'] == 1) {
                    $this->UserProfile->User->UserAvatar->validationErrors['filename'] = sprintf(__l('The file uploaded is too big, only files less than %s permitted') , ini_get('upload_max_filesize'));
                }
                $this->Session->setFlash(__l('User Profile could not be updated. Please, try again.') , 'default', null, 'error');
            }
            $user = $this->UserProfile->User->find('first', array(
                'conditions' => array(
                    'User.id' => $this->request->data['User']['id']
                ) ,
                'contain' => array(
                    'UserProfile' => array(
                        'fields' => array(
                            'UserProfile.id'
                        )
                    ) ,
                    'UserAvatar' => array(
                        'fields' => array(
                            'UserAvatar.id',
                            'UserAvatar.filename',
                            'UserAvatar.dir',
                            'UserAvatar.width',
                            'UserAvatar.height'
                        )
                    ) ,
                ) ,
                'recursive' => 0
            ));
			
            if (!empty($user['User'])) {
                unset($user['UserProfile']);
                $this->request->data['User'] = array_merge($user['User'], $this->request->data['User']);
                $this->request->data['UserAvatar'] = $user['UserAvatar'];
            }
        } else {
            if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
                $user_id = $this->Auth->user('id');
            } else {
                $user_id = $user_id ? $user_id : $this->Auth->user('id');
            }
            $this->request->data = $this->UserProfile->User->find('first', array(
                'conditions' => array(
                    'User.id' => $user_id
                ) ,
                'fields' => array(
                    'User.id',
                    'User.username',
                    'User.user_type_id',
                    'User.user_openid_count',
                    'User.user_login_count',
                    'User.user_view_count',
                    'User.is_active',
                    'User.is_email_confirmed',
                    'User.email',
					'User.latitude',
					'User.longitude',
					'User.fb_user_id'
                ) ,
                'contain' => array(
                    'UserAvatar' => array(
                        'fields' => array(
                            'UserAvatar.id',
                            'UserAvatar.dir',
                            'UserAvatar.filename',
                            'UserAvatar.width',
                            'UserAvatar.height'
                        )
                    ) ,
                    'UserWebsite' => array(
                        'fields' => array(
                            'UserWebsite.id',
                            'UserWebsite.website'
                        )
                    ) ,
                    'UserProfile' => array(
                        'fields' => array(
                            'UserProfile.first_name',
                            'UserProfile.last_name',
                            'UserProfile.middle_name',
                            'UserProfile.gender_id',
                            'UserProfile.about_me',
                            'UserProfile.address',
							'UserProfile.address1',
                            'UserProfile.country_id',
                            'UserProfile.state_id',
                            'UserProfile.city_id',
                            'UserProfile.zip_code',
                            'UserProfile.dob',
                            'UserProfile.language_id',
                            'UserProfile.paypal_account',
                            'UserProfile.paypal_first_name',
                            'UserProfile.paypal_last_name'
                        ) ,
                        'City' => array(
                            'fields' => array(
                                'City.name'
                            )
                        ) ,
                        'State' => array(
                            'fields' => array(
                                'State.name'
                            )
                        ),
                        'Country' => array(
                            'fields' => array(
                                'Country.iso2'
                            )
                        ) ,
                    )
                ) ,
                'recursive' => 2
            ));
			//print "<pre>";
			//print_r($this->request->data);
            if (!empty($this->request->data['UserProfile']['City'])) {
                $this->request->data['City']['name'] = $this->request->data['UserProfile']['City']['name'];
            }
            if (!empty($this->request->data['UserProfile']['State']['name'])) {
                $this->request->data['State']['name'] = $this->request->data['UserProfile']['State']['name'];
            }
        }
        $this->pageTitle.= ' - ' . $this->request->data['User']['username'];
        $genders = $this->UserProfile->genderOptions;
		$countries = $this->UserProfile->Country->find('list', array(
            'fields' => array(
                'Country.iso2',
                'Country.name'
            ) ,
            'order' => array(
                'Country.name' => 'ASC'
            )
        ));
        $translantions = array();
		$translantions = $this->UserProfile->Language->Translation->find('all', array(
            'conditions' => array(
                'Translation.is_verified' => 1
            ) ,
			'fields' => array(
                'DISTINCT Translation.language_id',
            ),
			'recursive' => -1,
        ));
        $translantion_id = array();
        foreach($translantions as $translantion){
        	$translantion_id[] = $translantion['Translation']['language_id'];
		}
        $languages = $this->UserProfile->Language->find('list', array(
            'conditions' => array(
                'Language.is_active' => 1,
                'Language.id' => $translantion_id,
            )
        ));
        $this->set(compact('genders', 'countries', 'languages'));
		
    }
    public function admin_edit($id = null)
    {
        if (is_null($id) && empty($this->request->data)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->setAction('edit', $id);
    }
    public function admin_user_account($user_id = null)
    {
        $this->pageTitle = __l('My Account');
        if (is_null($user_id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->set('pageTitle', $this->pageTitle);
        $this->set('user_id', $user_id);
        //$this->setAction('my_account', $user_id);
    }
}
?>